from course import models
from rest_framework import serializers

class Category(serializers.ModelSerializer):
    class Meta:
        model = models.CategoryModel
        fields = ["cname","id"]

class CategorySerializer(serializers.ModelSerializer):
    children=Category(many=True)
    class Meta:
        model = models.CategoryModel
        fields = '__all__'


#课程列表序列化
class CourseSerializer(serializers.ModelSerializer):
    tea=serializers.SerializerMethodField(read_only=True)
    def get_tea(self,obj):
        return {"tname":obj.teacher.tname,"job":obj.teacher.job,"intro":obj.teacher.intro,"headimg":"http://127.0.0.1:8000"+str(obj.teacher.headimg)}
    class Meta:
        model = models.CourseModel
        fields = '__all__'

class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.BrandModel
        fields = '__all__'

class BrandImage(serializers.Serializer):
    image=serializers.ImageField()

class BannerImage(serializers.Serializer):
    file=serializers.ImageField()
    def validate(self, attrs):
        #print(attrs)
        if attrs["file"].size>1024*1024*2:
            raise serializers.ValidationError("文件大小不能超过2M")
        return attrs


#索引的序列化器
from drf_haystack.serializers import HaystackSerializer
from .search_indexes import CourseIndex
class CourseIndexSerializer(HaystackSerializer):
    class Meta:
        index_classes = [CourseIndex]
        fields = ["text","id","cname","content","teacher","cover","price","discount"]

